import route from 'koa-route';
import fs from 'fs';
import path from 'path';
import { Globel } from '../lib/tools';
const getAllUser = route.get('/allUsers', async (ctx) => {
    let room_id = ctx.request.query.roomid as string;
    let room = Globel.rooms.get(room_id);
    if(!room){
        ctx.body = [];
    }else{
        let playerList: string[] = []
        room.game.playerMap.forEach(v => { playerList.push(v.userid) })
        ctx.body = playerList;
    }
})

const getUserInfo = route.get('/gameUserinfo', async (ctx) => {
    let userid = ctx.request.query.id as string;
    let room_id = ctx.request.query.roomid as string;
    let room = Globel.rooms.get(room_id);
    if(!room){
        ctx.body = {
            status:0,
            message:'未找到房间'
        }
    }else{
        ctx.body = room.game.playerMap.get(userid);
    }
})

const userLogin = route.post('/login', async (ctx) => {
    let userinfo: any = ctx.request.body;
    let userdata = JSON.parse(await fs.readFileSync(path.resolve(__dirname, "../static/userdata.json")).toString());
    let flag = false;
    for (let key in userdata) {
        if (userdata[key].username == userinfo.username||userdata[key].phone_number == userinfo.username) {
            if (userdata[key].password == userinfo.password) {
                let resUser = Object.assign({},userdata[key]);
                delete resUser.password;
                ctx.body = {
                    status: 1,
                    data:resUser,
                    message: '登录成功'
                }
            } else {
                ctx.status = 401;
                ctx.body = {
                    status: 0,
                    message: '用户名或密码不正确'
                }
            }
            flag = true;
            break;
        }
    }
    if (!flag) {
        ctx.status = 401;
        ctx.body = {
            status: 0,
            message: '用户不存在'
        }
    }
})
export default {
    getAllUser,
    getUserInfo,
    userLogin
};